Skip to main content
The Code Node allows you to build and execute custom Python functions. Use the Code node instead of the function calling code block in LLM Tools if you want a more deterministic pipeline (In function calling your LLM will reason to determine if it makes sense to call the function).

Important Notes

  1. Function must be called main()
    • Only a single root function is allow
      • Nested Functions are allowed
    • main() does not take any arguements
  2. Output from Code Node will be stored as CODE_id
    • a return statement is required to output from the code node
    • return output
  3. Outputs from previous nodes or variables can be passed in using standard variable naming convention
    • <?REPLACE_WITH_REF_NODE_ID?>

Allowed functionality with Code Node:

  1. Built-In Python Functions
    • int, str, isinstance, range, len, type, sum, round, ord, float, abs, min, max, all, any, sorted, enumerate, zip, filter, map, reversed, chr, divmod, pow, bin, hex, and oct
  2. Supported Packages
    • json, requests, datetime, time, re, hashlib, bs4, typing, contextlib, decimal
NOTE: in order to use these packages, you will need to import them into your code at the top

Following are commonly used examples:


Use Case: Webscraping with BeautifulSoup

import requests
from bs4 import BeautifulSoup
import json
import re

def main():
    url = "https://example.com/product-page"  # Replace with actual product page URL
    response = requests.get(url)
    
    # Parse the HTML content
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Assume the product data is embedded in a script tag or fetched via AJAX
    script_tag = soup.find('script', text=re.compile('window.__PRODUCT_DATA__'))
    
    if script_tag:
        # Extract JSON string from the script tag
        json_text = re.search(r'window\.__PRODUCT_DATA__\s*=\s*({.*?});', script_tag.string).group(1)
    else:
        # If script tag not found, assume data was fetched via AJAX
        ajax_url = "https://example.com/api/product"  # Replace with actual AJAX endpoint
        ajax_response = requests.get(ajax_url)
        json_text = ajax_response.text
    
    # Instance check to determine if input is a JSON string or a Python dictionary
    if isinstance(json_text, str):
        product_data = json.loads(json_text)  # Parse the JSON string into a Python dictionary
    elif isinstance(json_text, dict):
        product_data = json_text  # Already a dictionary, no need to parse
    else:
        raise ValueError("Input must be a JSON string or a Python dictionary")
    
    # Extract specific product details
    product_name = product_data.get('name', 'Unknown')
    product_price = product_data.get('price', 'Unavailable')
    
    output = {
        "Product Name": product_name,
        "Product Price": product_price
    }
    
    return json.dumps(output, indent=4)


I